import fly from './request'
import { Toast } from 'vant'
import store from '@/store'
/**
 * ajax请求
 * @param {string} url - url地址
 * @param {string} method - 方法 get post put delete
 * @param {object} data - 数据
 * @param {object} headers - headers
 */
const ajax = (url = '', method = 'get', data = {}, headers = { 'Content-Type': 'multipart/form-data' }) => {
  let formData
  if (method === 'post') {
    formData = new FormData()
    Object.entries(data).forEach(([key, value]) => {
      formData.append(key, value)
    })
  } else {
    formData = data
  }

  return fly.request(url, formData, { method, headers }).then((res) => {
    if (res.code === 200) {
      // 请求正常
      return Promise.resolve(res.data)
    } else {
      if (res.code === 40029 || res.code === 401) {
        Toast('请重新登录')
        store.dispatch('logout')
      } else {
        Toast(res.message)
      }
      return Promise.reject(res)
    }
  })
}

export default ajax
